package com.ruoyi.business.controller;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.manage.AsyncFactory;
import com.ruoyi.business.request.TaskAuditReq;
import com.ruoyi.business.request.TaskCreateReq;
import com.ruoyi.business.request.TaskExportReq;
import com.ruoyi.business.request.TaskUpdateReq;
import com.ruoyi.business.response.TaskExportRes;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelHelper;
import com.ruoyi.framework.manager.AsyncManager;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Task;
import com.ruoyi.business.service.ITaskService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 任务Controller
 *
 * @author Eric
 * @date 2024-03-17
 */
@RestController
@RequestMapping("/business/task")
public class TaskController extends BaseController {
    @Resource
    private ITaskService taskService;

    /**
     * 查询任务列表
     */
    @PreAuthorize("@ss.hasPermi('business:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(Task task) {
        startPage();
        List<Task> list = taskService.list(Wrappers.lambdaQuery(Task.class).setEntity(task));
        return getDataTable(list);
    }

    /**
     * 导出任务列表
     */
    @PreAuthorize("@ss.hasPermi('business:task:export')")
    @Log(title = "任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskExportReq req) {

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
        String exportPath = StrUtil.format("{}/{}", filePath, "export");
        String exportFilePath = StrUtil.format("{}/{}", exportPath, fileName);
        FileUtil.mkParentDirs(exportFilePath);

        List<TaskExportRes> exportList = taskService.getExportList(req, exportFilePath);
        ExcelHelper.export2File(exportFilePath, fileName, "任务", TaskExportRes.class, exportList);

        ZipUtil.zip(exportFilePath);
        FileUtils.downloadZip(exportFilePath + ".zip", response);

//        String downloadName = fileName + ".zip";
//        response.setContentType("application/zip; charset=UTF-8");
//        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + downloadName);


//        List<Task> list = taskService.list(Wrappers.lambdaQuery(Task.class).setEntity(task));
//        ExcelUtil<Task> util = new ExcelUtil<Task>(Task.class);
//        util.exportExcel(response, list, "任务数据");
    }

    /**
     * 获取任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(taskService.getTaskById(id));
    }

    /**
     * 新增任务
     */
    @PreAuthorize("@ss.hasPermi('business:task:add')")
    @Log(title = "任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated TaskCreateReq req) {
        req.setSource(0);
        return toAjax(taskService.createTask(req));
    }

    /**
     * 修改任务
     */
    @PreAuthorize("@ss.hasPermi('business:task:edit')")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated TaskUpdateReq req) {
        return toAjax(taskService.updateTask(req));
    }

    /**
     * 删除任务
     */
    @PreAuthorize("@ss.hasPermi('business:task:remove')")
    @Log(title = "任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(taskService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 提交任务
     *
     * @param taskId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:task:submit')")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/submit")
    public AjaxResult submitTask(@RequestParam Long taskId) {
        return toAjax(taskService.submitAuditTask(taskId));
    }

    /**
     * 审核任务
     *
     * @param req
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:task:audit')")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/audit")
    public AjaxResult auditTask(@RequestBody @Validated TaskAuditReq req) {
        return toAjax(taskService.auditTask(req));
    }

    /**
     * 完成任务
     *
     * @param taskId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:task:end')")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/end")
    public AjaxResult endTask(@RequestParam Long taskId) {
        return toAjax(taskService.end(taskId));
    }


    @GetMapping("/point/{taskId}")
    public AjaxResult getPointByTask(@PathVariable Long taskId) {
        return AjaxResult.success(taskService.getPointByTask(taskId));
    }

    @GetMapping("/survey/{pointId}")
    public AjaxResult getSurveyByPointId(@PathVariable Long pointId, Long userId) {
        return AjaxResult.success(taskService.getSurveyByPointId(pointId, userId));
    }

    @GetMapping("/select")
    public AjaxResult selectTaskUser(@RequestParam Long planId, String name) {
        return success(taskService.selectTaskUser(planId, name));
    }

    @PreAuthorize("@ss.hasPermi('business:task:syncData')")
    @PostMapping("/syncData/{ids}")
    public AjaxResult syncData(@PathVariable Long[] ids){
        LambdaUpdateWrapper<Task> updateWrapper = Wrappers.lambdaUpdate(Task.class)
                .in(Task::getId, ids)
                .eq(Task::getSyncStatus, 0)
                .set(Task::getSyncStatus, 2);
        taskService.update(updateWrapper);
        AsyncManager.me().execute(AsyncFactory.syncData(ids));
        return AjaxResult.success();
    }
}
